package com.waikuai.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.waikuai.shop.entity.Product;
import com.waikuai.shop.entity.User;
import com.waikuai.shop.entity.UserFavorite;
import com.waikuai.shop.mapper.ProductMapper;
import com.waikuai.shop.mapper.UserFavoriteMapper;
import com.waikuai.shop.mapper.UserMapper;
import com.waikuai.shop.service.UserFavoriteService;
import com.waikuai.shop.vo.ProductSimpleVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户收藏服务实现类
 * @author waikuai
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserFavoriteServiceImpl extends ServiceImpl<UserFavoriteMapper, UserFavorite>
        implements UserFavoriteService {

    private final UserFavoriteMapper userFavoriteMapper;
    private final ProductMapper productMapper;
    private final UserMapper userMapper;

    @Override
    public List<ProductSimpleVO> getUserFavorites(Long userId) {
        try {
            List<UserFavorite> favorites = userFavoriteMapper.selectFavoritesWithProductByUserId(userId);
            return favorites.stream()
                    .filter(fav -> fav.getProduct() != null)
                    .map(fav -> convertToProductSimpleVO(fav.getProduct()))
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取用户收藏列表失败，用户ID: {}", userId, e);
            return new ArrayList<>();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addToFavorites(Long userId, Long productId) {
        try {
            // 验证商品是否存在
            if (!validateProductExists(productId)) {
                log.warn("商品不存在，商品ID: {}", productId);
                return false;
            }

            // 验证用户是否存在
            if (!validateUserExists(userId)) {
                log.warn("用户不存在，用户ID: {}", userId);
                return false;
            }

            // 检查是否已收藏
            if (isFavorited(userId, productId)) {
                log.info("商品已收藏，用户ID: {}, 商品ID: {}", userId, productId);
                return true;
            }

            UserFavorite favorite = new UserFavorite();
            favorite.setUserId(userId);
            favorite.setProductId(productId);

            int result = userFavoriteMapper.insert(favorite);
            if (result > 0) {
                log.info("添加商品收藏成功，用户ID: {}, 商品ID: {}", userId, productId);
                return true;
            }

            return false;
        } catch (Exception e) {
            log.error("添加商品收藏失败，用户ID: {}, 商品ID: {}", userId, productId, e);
            throw new RuntimeException("添加商品收藏失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeFromFavorites(Long userId, Long productId) {
        try {
            int result = userFavoriteMapper.deleteFavorite(userId, productId);
            if (result > 0) {
                log.info("取消商品收藏成功，用户ID: {}, 商品ID: {}", userId, productId);
                return true;
            }

            return false;
        } catch (Exception e) {
            log.error("取消商品收藏失败，用户ID: {}, 商品ID: {}", userId, productId, e);
            throw new RuntimeException("取消商品收藏失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchRemoveFromFavorites(Long userId, List<Long> productIds) {
        try {
            if (productIds == null || productIds.isEmpty()) {
                return true;
            }

            int totalDeleted = 0;
            for (Long productId : productIds) {
                int result = userFavoriteMapper.deleteFavorite(userId, productId);
                totalDeleted += result;
            }

            if (totalDeleted > 0) {
                log.info("批量取消收藏成功，用户ID: {}, 删除数量: {}", userId, totalDeleted);
                return true;
            }

            return false;
        } catch (Exception e) {
            log.error("批量取消收藏失败，用户ID: {}", userId, e);
            throw new RuntimeException("批量取消收藏失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean clearFavorites(Long userId) {
        try {
            int result = userFavoriteMapper.clearFavoritesByUserId(userId);
            if (result > 0) {
                log.info("清空用户收藏成功，用户ID: {}, 清空数量: {}", userId, result);
                return true;
            }

            return false;
        } catch (Exception e) {
            log.error("清空用户收藏失败，用户ID: {}", userId, e);
            throw new RuntimeException("清空用户收藏失败");
        }
    }

    @Override
    public boolean isFavorited(Long userId, Long productId) {
        try {
            UserFavorite favorite = userFavoriteMapper.selectByUserIdAndProductId(userId, productId);
            return favorite != null;
        } catch (Exception e) {
            log.error("检查用户是否已收藏该商品失败，用户ID: {}, 商品ID: {}", userId, productId, e);
            return false;
        }
    }

    @Override
    public Integer countUserFavorites(Long userId) {
        try {
            return userFavoriteMapper.countFavoritesByUserId(userId);
        } catch (Exception e) {
            log.error("统计用户收藏数量失败，用户ID: {}", userId, e);
            return 0;
        }
    }

    @Override
    public Integer countProductFavorites(Long productId) {
        try {
            return userFavoriteMapper.countFavoritesByProductId(productId);
        } catch (Exception e) {
            log.error("统计商品收藏数量失败，商品ID: {}", productId, e);
            return 0;
        }
    }

    @Override
    public List<Long> getProductFavoriteUserIds(Long productId) {
        try {
            return userFavoriteMapper.selectUserIdsByProductId(productId);
        } catch (Exception e) {
            log.error("获取商品收藏用户ID列表失败，商品ID: {}", productId, e);
            return new ArrayList<>();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean toggleFavorite(Long userId, Long productId) {
        try {
            if (isFavorited(userId, productId)) {
                return removeFromFavorites(userId, productId);
            } else {
                return addToFavorites(userId, productId);
            }
        } catch (Exception e) {
            log.error("切换收藏状态失败，用户ID: {}, 商品ID: {}", userId, productId, e);
            throw new RuntimeException("切换收藏状态失败");
        }
    }

    @Override
    public UserFavorite getByUserIdAndProductId(Long userId, Long productId) {
        try {
            return userFavoriteMapper.selectByUserIdAndProductId(userId, productId);
        } catch (Exception e) {
            log.error("根据用户ID和商品ID查询收藏记录失败，用户ID: {}, 商品ID: {}", userId, productId, e);
            return null;
        }
    }

    @Override
    public List<Long> getUserFavoriteProductIds(Long userId) {
        try {
            List<UserFavorite> favorites = userFavoriteMapper.selectFavoritesWithProductByUserId(userId);
            return favorites.stream()
                    .filter(fav -> fav.getProduct() != null)
                    .map(UserFavorite::getProductId)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取用户收藏的商品ID列表失败，用户ID: {}", userId, e);
            return new ArrayList<>();
        }
    }

    @Override
    public boolean validateProductExists(Long productId) {
        try {
            Product product = productMapper.selectById(productId);
            return product != null && product.getStatus() == 1; // 只验证上架的商品
        } catch (Exception e) {
            log.error("验证商品是否存在失败，商品ID: {}", productId, e);
            return false;
        }
    }

    @Override
    public boolean validateUserExists(Long userId) {
        try {
            // 需要通过UserMapper查询用户信息，而不是UserFavoriteMapper
            User user = userMapper.selectById(userId);
            return user != null && user.getStatus() == 1; // 只验证启用的用户
        } catch (Exception e) {
            log.error("验证用户是否存在失败，用户ID: {}", userId, e);
            return false;
        }
    }

    /**
     * 转换为商品简单信息视图对象
     */
    private ProductSimpleVO convertToProductSimpleVO(Product product) {
        try {
            ProductSimpleVO vo = new ProductSimpleVO();
            vo.setId(product.getId());
            vo.setProductName(product.getProductName());
            vo.setMainImage(product.getMainImage());
            vo.setPrice(product.getPrice());
            vo.setOriginalPrice(product.getOriginalPrice());
            vo.setSalesCount(product.getSalesCount());
            vo.setStockQuantity(product.getStockQuantity());
            vo.setIsFeatured(product.getIsFeatured());
            vo.setStatus(product.getStatus());

            // 计算折扣百分比
            if (product.getOriginalPrice() != null && product.getOriginalPrice().compareTo(java.math.BigDecimal.ZERO) > 0) {
                java.math.BigDecimal discount = product.getOriginalPrice().subtract(product.getPrice());
                BigDecimal discountPercent = discount.divide(product.getOriginalPrice(), 2, RoundingMode.HALF_UP)
                        .multiply(new java.math.BigDecimal("100"));
                vo.setDiscountPercentage(discountPercent.intValue());
            }

            return vo;
        } catch (Exception e) {
            log.error("转换商品简单信息失败: {}", e.getMessage(), e);
            return new ProductSimpleVO();
        }
    }
}